package pro.lingwu.station.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import pro.lingwu.station.dao.UserMapper;
import pro.lingwu.station.dto.db.User;
import pro.lingwu.station.service.UserService;
import pro.lingwu.station.utils.FileUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 *
 * @author @lingwu
 * @date created in 2021/11/17
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper mapper;

    private final FileUtils fileUtils;

    public UserServiceImpl(UserMapper mapper,
                           FileUtils fileUtils){
        this.mapper = mapper;
        this.fileUtils = fileUtils;
    }

    @Override
    public void addUser(User user, MultipartFile file) throws IOException {
        String avatar = fileUtils.storeFile(user.getAccount(), file);
        user.setAvatar(avatar);
        mapper.addUser(user);
    }

    @Override
    public User signIn(HttpServletRequest request, String account, String password) {
        User user = mapper.findUserBy(account);
        if(user!=null && user.getPassword().equals(password)){
            /*BoundValueOperations<String, String> ops =
                    redisTemplate.boundValueOps("sign-in:" + account);
            ops.set(session.getId());*/
            HttpSession session = request.getSession();
            session.setAttribute("sign-in", true);
            return user;
        }
        return null;
    }

    @Override
    public void updateUser(User user, MultipartFile file) throws IOException {
        User user1 = mapper.findUserBy(user.getAccount());
        if (user1 == null) {
            // 失败
        }
        if (file != null){
            String filename = fileUtils.storeFile(user.getAccount(), file);
            user.setAvatar(filename);
        }
        mapper.updateUser(user);
    }
}
